package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class TransactionAdapter extends SimpleCursorAdapter {
	private static SimpleDateFormat mReadFormat = new SimpleDateFormat("yyyy-MM-dd");
	private static DateFormat mWriteFormat = DateFormat.getDateInstance(DateFormat.SHORT);
	private static NumberFormat mMoneyFormat = NumberFormat.getCurrencyInstance();
	
	public TransactionAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
		super(context, layout, c, from, to);
		mMoneyFormat.setCurrency(Buxoid.mDb.getCurrency());
	}

	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = super.getView(position, convertView, parent);
		Cursor c = super.getCursor();
		int status = c.getInt(c.getColumnIndexOrThrow(BuxoidDb.TRANS_STATUS));
		
		if (status == BuxoidDb.TRANS_STATUS_PENDING) {
			v.setBackgroundResource(R.drawable.trans_pending);
		} 
		return v;
	}


	@Override
	public void setViewText(TextView v, String text) {
		int id = v.getId();
		Cursor c = super.getCursor();
		if (id == R.id.row_trans_date) {
			try {
				text = mWriteFormat.format(mReadFormat.parse(text));
			} catch (ParseException e) {
//				Log.d(getClass().getSimpleName(), "Could not parse date");
			}
			v.setText(text);
		} else if (id == R.id.row_trans_amount) {
			String type = c.getString(c.getColumnIndexOrThrow(BuxoidDb.TRANS_TYPE));
			double amount = Double.parseDouble(text);
			if (type.equals("expense")) {
				amount = -amount;
			}
			text = mMoneyFormat.format(amount);
			v.setText(text);
		} else {
			super.setViewText(v, text);
		}
	}
}
